package com.movies.repository;

import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;

import java.io.InputStream;
import java.util.List;

/**
 * Created by admin on 2017/4/9.
 */
@Repository
public class MongoRepository {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    public String saveFile(InputStream content, String filename, String contentType, DBObject metaData) {
        return gridFsTemplate.store(content, filename, contentType, metaData).getId().toString();
    }

    public List<GridFSDBFile> findAll() {
        return gridFsTemplate.find(null);
    }

    public GridFSDBFile find(String name) {
        return gridFsTemplate.findOne(new Query(Criteria.where("filename").is(name)));
    }

    public GridFSDBFile findById(String postId) {
        return gridFsTemplate.findOne(new Query(Criteria.where("_id").is(postId)));
    }

    public void deleteById(String postId) {
        gridFsTemplate.delete(new Query(Criteria.where("_id").is(postId)));
    }
}
